package DataStructure.list;


//顺序表
public class SeqList<E> implements MyList<E>{
    private E[] e;//元素数组
    private int size;


    public SeqList() {
        e= (E[]) new Object[4];
        size=0;
    }

    //扩充容量
    private void grow(){
        E[] tmp=e;
        e=(E[]) new Object[size*2];
        for (int i = 0; i < size; i++) {
            e[i]=tmp[i];
        }
    }

    //缩减容量
    private void cut(){

    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public boolean contains(E element) {
        return indexOf(element)!=-1;
    }

    @Override
    public boolean add(E element) {
        add(size,element);
        return true;
    }

    @Override
    public void add(int index, E element) {
        if(index<0||index>size)
            return;
        //判断需要扩容
        if(size==e.length)
            grow();
        //移动元素
        for (int i = size; i > index; i--) {
            e[i]=e[i-1];
        }
        e[index]=element;
        size++;
    }

    @Override
    public boolean remove(E element) {
        int index=indexOf(element);
        //判断存在
        if(index==-1)
            return false;
        remove(index);
        return true;
    }

    @Override
    public E remove(int index) {
        if(index<0||index>=size)
            return null;
        E tmp=e[index];
        //移动元素
        for (int i = index; i < size-1; i++) {
            e[i]=e[i+1];
        }
        size--;
        return tmp;
    }

    @Override
    public E get(int index) {
        if(index<0||index>=size)
            return null;
        return e[index];
    }

    @Override
    public int indexOf(E element) {
        for (int i = 0; i < size; i++) {
            if(e[i].equals(element))
                return i;
        }
        return -1;
    }

    @Override
    public E set(int index, E element) {
        if(index<0||index>=size)
            return null;
        E tmp=e[index];
        e[index]=element;
        return tmp;
    }

    @Override
    public void clear() {
        e= (E[]) new Object[4];
        size=0;
    }

    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder("[");
        for (int i = 0; i < size; i++) {
            sb.append(e[i]);
            if(i!=size-1)
                sb.append(",");
        }
        sb.append("]");

        return "SeqList{" +
                "e=" + sb +
                ", size=" + size +
                '}';
    }
}
